package com.jiangnan.ui.fragment

import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.IInterface
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.chad.library.adapter4.BaseQuickAdapter
import com.jiangnan.R
import com.jiangnan.databinding.FragmentReturnBinding
import com.jiangnan.entity.Book
import com.jiangnan.ui.activity.BookMainActivity
import com.jiangnan.ui.activity.UserBorrowBookActivity
import com.jiangnan.ui.adapter.ReturnBookQuickAdapter
import com.jiangnan.ui.adapter.UserBorrowBookInfoQuickAdapter
import com.jiangnan.util.CurrentHolder
import com.jiangnan.util.CurrentLoginInfo
import com.jiangnan.util.NavigationUtil
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.viewmodel.AdminViewModel
import com.jiangnan.viewmodel.AuthViewModel
import com.jiangnan.viewmodel.BookViewModel
import com.jiangnan.viewmodel.CreditViewModel
import com.jiangnan.viewmodel.UserViewModel
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [ReturnFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class ReturnFragment : Fragment(), View.OnClickListener {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null

    private lateinit var binding: FragmentReturnBinding
    private lateinit var bookViewModel: BookViewModel
    private lateinit var authViewModel: AuthViewModel
    private lateinit var adminViewModel: AdminViewModel
    private lateinit var creditViewModel: CreditViewModel
    private lateinit var userViewModel: UserViewModel
    private var currentUserRole: Int? = 0
    private var currentUserId: Long? = 0L
    private var maxBorrowDays: Int? = null
    private var adapter: ReturnBookQuickAdapter? = null
    private var adminAdapter: UserBorrowBookInfoQuickAdapter? = null
    private var totalBorrowBookNum: Int = 0
    private var page: Int = 1
    private var pageSize: Int = 10
    private var requestParam: String = ""
    private val TAG = "ReturnFragment"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate<FragmentReturnBinding>(
            inflater,
            com.jiangnan.R.layout.fragment_return,
            container,
            false
        )
        bookViewModel = ViewModelProvider(this).get(BookViewModel::class.java)
        authViewModel = ViewModelProvider(this).get(AuthViewModel::class.java)
        adminViewModel = ViewModelProvider(this).get(AdminViewModel::class.java)
        creditViewModel = ViewModelProvider(this)[CreditViewModel::class.java]
        userViewModel = ViewModelProvider(this)[UserViewModel::class.java]
        SharedPrefUtil.getLoginInfo(requireContext()).let{
            currentUserId = it!!.id.toLong()
            currentUserRole = it.role
        }
//        currentUserId = CurrentLoginInfo.getCurrentLoginInfo()!!.id.toLong()
//        currentUserRole = CurrentLoginInfo.getCurrentLoginInfo()!!.role
        // 搜索框的焦点变化监听器
        if (currentUserRole == 0) {
            initItem(page, pageSize, requestParam)
            searchFragmentSelector()
            initAdminObserver()
            initAdminRefreshLayout()
            initAdminAdapter()

        }
        if (currentUserRole == 1) {
            // 初始化监听器
            initObserver()
            initRefreshLayout()
            binding.returnFlSearchLayout.visibility = View.GONE
            binding.ivClear.visibility = View.GONE
        }
        toastMessage()

        binding.tvSearch.setOnClickListener(this)
        binding.ivClear.setOnClickListener(this)

        return binding.root
    }

    /**
     * 初始化列表
     */
    private fun initItem(page: Int, pageSize: Int, requestParam: String) {
        adminViewModel.getUserInfoList(page, pageSize, requestParam)

    }

    private fun initAdminAdapter() {
        var recyclerView = binding.recyclerView
        recyclerView.layoutManager = StaggeredGridLayoutManager(
            1, StaggeredGridLayoutManager.VERTICAL
        )
        adminAdapter = UserBorrowBookInfoQuickAdapter()
        adminAdapter!!.setItemAnimation(BaseQuickAdapter.AnimationType.AlphaIn)
        recyclerView.adapter = adminAdapter

        adminAdapter!!.setOnItemClickListener { _, view, position ->
            val intent = Intent(requireContext(), UserBorrowBookActivity::class.java)
            intent.putExtra("userId", adminAdapter!!.getItem(position)?.id!!.toLong())
            startActivity(intent)
        }

        // 需要传递控件 id 子view
        adminAdapter!!.addOnItemChildClickListener(R.id.status_active) { _, view, position ->
            adminViewModel.updateUserStatus(adminAdapter!!.getItem(position)?.id!!, 1)
        }
        adminAdapter!!.addOnItemChildClickListener(R.id.status_blocked) { _, view, position ->
            adminViewModel.updateUserStatus(adminAdapter!!.getItem(position)?.id!!, 0)
        }
    }

    private fun initAdminRefreshLayout() {
        val refreshLayout = binding.refreshLayout as RefreshLayout
        refreshLayout.setRefreshHeader(ClassicsHeader(context))
        refreshLayout.setRefreshFooter(ClassicsFooter(context))
        refreshLayout.setOnRefreshListener { refreshlayout ->
            page = 1
            initItem(page, pageSize, requestParam)
            refreshlayout.finishRefresh(true)
        }

        refreshLayout.setOnLoadMoreListener { refreshlayout ->
//            ToastUtil.showShort(requireContext(), "共有数据条数为 ${adminViewModel.userInfoPageResult.value!!.data!!.total}")
            if (page * pageSize < adminViewModel.userInfoPageResult.value!!.data!!.total) {
                page = page.plus(1)
                initItem(page, pageSize, requestParam)
                refreshlayout.finishLoadMore(true)
            } else {
                ToastUtil.showShort(requireContext(), "没有更多数据了")
                refreshlayout.finishLoadMore(false)
            }
        }
    }

    private fun initAdminObserver() {
        adminViewModel.userInfoPageResult.observe(viewLifecycleOwner) {
            if (requestParam == "") {
                binding.tvTotal.text = "本馆用户数量为 ${it.data!!.total} 人"
            }else{
                binding.tvTotal.text = "符合条件的用户数量为 ${it.data!!.total} 人"
            }

            adminAdapter!!.submitList(it.data!!.rows)
        }

        adminViewModel.updateUserStatusResponse.observe(viewLifecycleOwner) {
            if (it.code == 1) {
                ToastUtil.showShort(requireContext(), "用户状态更新成功")
            } else {
                ToastUtil.showShort(requireContext(), "用户状态更新失败")
            }
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun getFormattedCurrentTime(): String {
        // 获取当前时间
        val current = LocalDateTime.now(ZoneId.systemDefault())

        // 创建一个格式化器，用于生成ISO 8601格式的字符串
        val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss")

        // 格式化当前时间
        return current.format(formatter)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initAdapter() {
        var recyclerView = binding.recyclerView
        recyclerView.layoutManager = StaggeredGridLayoutManager(
            1, StaggeredGridLayoutManager.VERTICAL
        )
        adapter = maxBorrowDays?.let { ReturnBookQuickAdapter(it) }
        adapter?.setItemAnimation(BaseQuickAdapter.AnimationType.AlphaIn)
        recyclerView.adapter = adapter

        // 需要传递控件 id
        adapter!!.addOnItemChildClickListener(R.id.btn_return) { _, view, position ->
            bookViewModel.returnBook(currentUserId!!, adapter!!.getItem(position)?.id!!)
            val returnDate = getFormattedCurrentTime()
            creditViewModel.returnBook(
                currentUserId!!,
                adapter!!.getItem(position)?.id!!.toLong(),
                adapter!!.getItem(position)?.operateDate!!,
                returnDate
            )
            Log.d(TAG, "initAdapter: 执行了")
        }
    }

    /**
     * 初始化下拉刷新和上拉加载
     */
    private fun initRefreshLayout() {
        val refreshLayout = binding.refreshLayout as RefreshLayout
        refreshLayout.setRefreshHeader(ClassicsHeader(context))
//        refreshLayout.setRefreshFooter(ClassicsFooter(context))
        refreshLayout.setOnRefreshListener { refreshlayout ->
            bookViewModel.fetchBorrowedBooks(currentUserId!!)
            refreshlayout.finishRefresh(true) //传入false表示刷新失败
        }
//        refreshLayout.setOnLoadMoreListener { refreshlayout ->
//            refreshlayout.finishLoadMore(200 /*,false*/) //传入false表示加载失败
//        }
    }

    /**
     * 所有的监听器在这里初始化
     */
    @RequiresApi(Build.VERSION_CODES.O)
    private fun initObserver() {
        bookViewModel.fetchBorrowedBooks(currentUserId!!)
        userViewModel.loadUserCertificate(currentUserId!!)

        userViewModel.userCertificate.observe(viewLifecycleOwner) {
            maxBorrowDays = it.maxBorrowDay
            initAdapter()
            bookViewModel.borrowedBooks.observe(viewLifecycleOwner) {
                binding.tvTotal.text = "待归还图书 " + it.size.toString() + " 本"
                adapter!!.submitList(it)
            }
        }

        /**
         * 监听返回结果
         */
        bookViewModel.returnResponse.observe(viewLifecycleOwner) {
            bookViewModel.fetchBorrowedBooks(currentUserId!!)
        }




    }

    private fun toastMessage() {
        bookViewModel.toastMessage.observe(viewLifecycleOwner) { event ->
            event.getContentIfNotHandled()?.let { message ->
                ToastUtil.showShort(requireContext(), message)
            }
        }
    }

    private fun searchFragmentSelector() {
        // 设置焦点变化监听器来恢复父容器的原始状态
        binding.returnEtSearch.onFocusChangeListener = View.OnFocusChangeListener { v, hasFocus ->
            if (!hasFocus) {
                // 当输入框失去焦点时，恢复父容器的原始背景
                binding.returnFlSearchLayout.setBackgroundResource(com.jiangnan.R.drawable.edittext_default_bg)
            } else {
                // 可选：如果需要，在获得焦点时也改变背景
                binding.returnFlSearchLayout.setBackgroundResource(com.jiangnan.R.drawable.edittext_pressed_bg)
            }
        }
    }



    override fun onClick(p0: View?) {
        when (p0?.id) {


            binding.tvSearch.id -> {
                requestParam = binding.returnEtSearch.text.toString()
                page = 1
                initItem(page, pageSize, requestParam)
//                ToastUtil.showShort(requireContext(), "点击了搜索按钮")
            }

            binding.ivClear.id -> {
                binding.returnEtSearch.text.clear()
                requestParam = ""
                page = 1
                initItem(page, pageSize, requestParam)
            }
        }
    }


    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment ReturnFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            ReturnFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}